package com.ruoyi.leave.instener;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 自定义跳槽跳转接口
 */
public class DynamicJumpCmd implements Command<Void> {
    private static final Logger log = LoggerFactory.getLogger(DynamicJumpCmd.class);
    private String processInstanceId;
    private String fromActivitiId;
    private String toActivitiId;

    public DynamicJumpCmd(String processInstanceId, String fromActivitiId, String toActivitiId) {
        this.processInstanceId = processInstanceId;
        this.fromActivitiId = fromActivitiId;
        this.toActivitiId = toActivitiId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        // 获取执行实例管理器
        ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();

        //获取主执行实例对象
        ExecutionEntity executionEntity = executionEntityManager.findById(processInstanceId);

        //删除当前任务对应的执行实例
        ExecutionEntity activitiExecutionEntity = null;
        // 找到所有的子执行实例
        List<ExecutionEntity> childs = executionEntityManager.findChildExecutionsByProcessInstanceId(processInstanceId);
        for (ExecutionEntity child : childs) {
            if (child.getCurrentActivityId().equals(fromActivitiId)) {
                activitiExecutionEntity = child;
                break;
            }
        }

        // bpmnModel 流程模型对象
        BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(executionEntity.getProcessDefinitionId());
        // 获取开始节点
        FlowElement fromFlowElement = bpmnModel.getFlowElement(fromActivitiId);
        FlowElement toFlowElement = bpmnModel.getFlowElement(toActivitiId);
        // 删除当前节点的执行实例和数据
        executionEntityManager.deleteExecutionAndRelatedData(activitiExecutionEntity, "驳回", false);
        //创建新的执行实例，绑定要调整的 toActivitiId
        ExecutionEntity childExecution = executionEntityManager.createChildExecution(executionEntity);
        childExecution.setCurrentFlowElement(toFlowElement);
        // Agenda 生效
        commandContext.getAgenda().planContinueMultiInstanceOperation(childExecution);
        return null;
    }
}
